In Svelte, a custom store is a store you create by implementing your own subscribe, set, and update logic, rather than using the built-in writable or readable stores directly. Custom stores allow you to encapsulate complex state logic, side effects, or asynchronous operations, making your state management more reusable and organized.
A custom store is typically an object with a subscribe method (required for all stores) and optional set or update methods. You can also include your own functions to modify the store.
You need to encapsulate complex state logic that involves multiple operations.
You want to include side effects like API calls, localStorage syncing, or timers inside the store.
You want reusable stores with helper methods beyond set and update.
You need derived or computed values tied to the store that shouldn’t clutter the component code.
Custom stores implement the store contract (subscribe method) and optionally include helper methods.
They allow encapsulating state logic and side effects outside components.
They improve reusability and keep component code cleaner.
They can be global (shared across routes) or scoped to a component depending on your needs.